package com.samphanie.admin.config;

import lombok.RequiredArgsConstructor;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.env.Environment;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;
import java.util.Collections;

/**
 * 全局跨域配置
 * @author ZSY
 * @date 2021/4/19 16:42
 */
@Configuration
@RequiredArgsConstructor
public class GlobalCorsConfig {

    private final Environment environment;

    @Bean
    public FilterRegistrationBean<CorsFilter> customCorsFilter() {
        // 1.添加CORS配置信息
        CorsConfiguration config = new CorsConfiguration();
        // 允许跨越发送cookie
        config.setAllowCredentials(true);
        // 允许域名进行跨域调用
        //        if (environment.acceptsProfiles(Profiles.of("dev"))) {
        //            config.setAllowedOrigins(Collections.singletonList("http://localhost:9527"));
        //        } else {
        //            config.setAllowedOrigins(Collections.singletonList("https://"));
        //        }
        config.addAllowedOriginPattern("*");
        // 放行全部原始头信息
        config.addAllowedHeader("*");
        config.setAllowedHeaders(Collections.singletonList("*"));
        config.addExposedHeader("X-Authenticate");
        // 允许所有请求方法跨域调用
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        // 设置访问时间
        config.setMaxAge(3600L);

        // 2.添加映射路径，我们拦截一切请求
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
        // 在使用 OAUTH Authorization Server 上，必须设置成最高优先级，否则 OAUTH2 Filter 会直接先拦截请求，使 CORS 设置失效
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return bean;
    }


}
